package com.dengqi.mymodule.activity.update;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;

import java.io.File;

import static android.content.Context.MODE_PRIVATE;

public class DownloadManagerUtil {
    private Context mContext;

    public DownloadManagerUtil(Context context) {
        mContext = context;
    }

    public long download(String url, String title, String desc) {
        //外部公有
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("download", MODE_PRIVATE);
        String apk_path = sharedPreferences.getString("apk_path", "");
        long apk_id = sharedPreferences.getLong("apk_id", -1);
        File file = new File(apk_path);
        if(file.exists()){
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, apk_id);
            intent.putExtra("apk_path", apk_path);
            intent.setAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            mContext.sendBroadcast(intent);
            return -1;
        }
        Uri uri = Uri.parse(url);
        DownloadManager.Request req = new DownloadManager.Request(uri);
        //设置WIFI下进行更新
        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //下载中和下载完后都显示通知栏
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //使用系统默认的下载路径 此处为应用内 /storage/emulated/0/Android/data/com.dengqi.mymodule/files/Download/测试应用.apk ,所以兼容7.0
        req.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, title);
//        下载路径为/storage/emulated/0/Download/测试应用.apk
//        req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title);
        //通知栏标题
        req.setTitle(title);
        //通知栏描述信息
        req.setDescription(desc);
        //设置类型为.apk
        req.setMimeType("application/vnd.android.package-archive");
        //获取下载任务ID
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        return dm.enqueue(req);
    }

    /**
     * 下载前先移除前一个任务，防止重复下载
     * @param downloadId
     */
    public void clearCurrentTask(long downloadId) {
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            dm.remove(downloadId);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
    }
}
